<template>
  <div class="message">
    <loading v-if="!userMessage" />
    <nodata v-else-if="!userMessage.length"></nodata>

    <el-tabs v-else>
      <el-tab-pane :label="setSystem() | findSystemStatus('系统消息')">
        <div class="system-message">
          <div class="title">系统消息</div>
          <ul>
            <li v-for="sys in setSystem()" :key="sys._id">
              <div class="send-user">
                <div class="img">
                  <img :src="sys.sendCoverUrl | squareUrls" alt />
                </div>
                <div class="content">
                  <h3>{{sys.sendUserName}}</h3>
                  <p>
                    TA在
                    <i>{{sys.label}}</i> 页面对你进行了回复：
                  </p>
                  <span class="status">{{sys.status ? "已查看": "未查看"}}</span>
                </div>
              </div>
              <div class="text">{{sys.text}}</div>
              <div class="look">
                <p>
                  你可以
                  <span class="this-click" @click="gotoPage(sys.type,sys.id)">点击这里</span>
                  进行查看并回复前往回复
                </p>
                <el-button size="mini" @click="toggleStatus(sys._id)">标记已查看</el-button>
              </div>
            </li>
          </ul>
        </div>
      </el-tab-pane>
      <el-tab-pane
        :label="userMessage | findUserData | findUserStatus('用户消息')"
        class="user-message"
      >
        <div class="message-table">
          <div class="title">
            <span>这里是其他用户发送给您的消息，请点击查看操作进行查看消息。</span>
          </div>
          <el-table :data="userMessage | findUserData">
            <el-table-column prop="sendCoverUrl" label="用户头像">
              <template slot-scope="scope">
                <div class="img">
                  <img :src="setImage(scope.row) | squareUrls" alt />
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="sendUserName" label="用户名"></el-table-column>
            <el-table-column label="发送日期">
              <template slot-scope="scope">{{setDate(scope.row)}}</template>
            </el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">{{setStatus(scope.row)}}</template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="small" @click="openThisMessage(scope.row)">查看</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-drawer
      :visible.sync="messageDrawer"
      size="30%"
      class="messgae-drawer"
      :with-header="false"
      v-if="drawerData && drawerData.sendUserName"
    >
      <loading v-if="!drawerData" />
      <nodata v-else-if="!drawerData.sendUserName"></nodata>
      <div v-else class="drawer-content">
        <div class="send-user">
          <div class="send-user-left">
            <img :src="drawerData.sendCoverUrl | squareUrls" alt />
          </div>
          <div class="send-user-right">
            <h3>{{drawerData.sendUserName}}</h3>
            <span>发送日期：{{drawerData.created | setDate}}</span>
          </div>
        </div>
        <div class="send-body">
          <p>{{drawerData.text}}</p>
        </div>
        <div class="return-message">
          <el-input
            class="return-textarea"
            v-if="returnFlog"
            v-model="returnText"
            type="textarea"
            :placeholder="userInfoData.name ? userInfoData.name + '：你想回复TA什么？' : userName + '：你想回复TA什么？'"
          ></el-input>
          <div class="btn">
            <el-button size="small" @click="showTextArea()">{{btnText}}</el-button>
            <el-button
              size="small"
              v-if="returnText && returnFlog"
              @click="returnMessageMethods()"
            >提交回复</el-button>
          </div>
          <div class="history">
            <loading v-if="!historyMessage" />
            <nodata v-else-if="!historyMessage.length" />
            <ul v-else>
              <h3 class="history-title">历史消息(倒序)：</h3>
              <li
                v-for="data in historyMessage"
                :key="data._id"
                :class="[data.userName === userName ? 'active' : '']"
              >
                <div class="history-message-wrapper">{{data.text}}</div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { mapState, mapActions } from "Vuex";
export default {
  name: "message",
  data() {
    return {
      messageDrawer: false,
      drawerData: "",
      returnFlog: false,
      btnText: "展开回复框",
      returnText: "",
      historyMessage: ""
    };
  },
  filters: {
    findUserData(data) {
      let newData = [];
      for (let i = 0; i < data.length; i++) {
        if (!data[i].system) {
          newData.push(data[i]);
        }
      }
      return newData;
    },
    findSystemStatus(data, text) {
      let number = 0;
      for (let i = 0; i < data.length; i++) {
        if (!data[i].status) {
          number++;
        }
      }
      if (number) {
        return text + "(" + number + ")";
      } else {
        return text;
      }
    },
    findUserStatus(data, text) {      
      let number = 0;
      for (let i = 0; i < data.length; i++) {
        if (!data[i].status) {
          number++;
        }
      }
      if (number) {
        return text + "(" + number + ")";
      } else {
        return text;
      }
    }
  },
  computed: {
    ...mapState("user", ["userMessage", "userInfoData", "userName"])
  },
  methods: {
    toggleStatus(_id) {
      this.toggleMessageStatus({ status: true, _id: _id }).then(res => {
        if (res.data.ok === 1) {
          this.getMessage({ userName: this.userName });
        }
      });
    },
    gotoPage(type, id) {
      this.$router.push(`/${type}/${id}`);
    },
    setSystem() {
      let data = this.userMessage;
      let newData = [];
      for (let i = 0; i < data.length; i++) {
        if (data[i].system) {
          newData.push(data[i]);
        }
      }
      return newData;
    },
    showTextArea() {
      this.returnFlog = !this.returnFlog;
      if (this.returnFlog) {
        this.btnText = "收起回复框";
      } else {
        this.btnText = "展开回复框";
      }
    },
    returnMessageMethods() {
      let data = {
        text: this.returnText,
        sendUserName: this.userName,
        userName: this.drawerData.sendUserName,
        sendCoverUrl: this.userInfoData.coverUrl
      };
      this.sendMessageToUser(data)
        .then(res => {
          this.returnText = "";
          this.getOneToOneMessage({
            userName: this.userName,
            sendUserName: this.drawerData.sendUserName
          }).then(res => {
            this.historyMessage = res.data.data;
          });
          this.$alert(res.data.data);
        })
        .catch(err => {
          console.log("错误信息：" + err);
        });
    },
    openThisMessage(row) {
      this.drawerData = row;
      this.messageDrawer = true;

      // 获取一对一的消息历史记录。
      this.getOneToOneMessage({
        userName: this.userName,
        sendUserName: this.drawerData.sendUserName
      }).then(res => {
        this.historyMessage = res.data.data;
      });

      this.toggleMessageStatus({ status: true, _id: row._id }).then(res => {
        if (res.data.ok === 1) {
          this.getMessage({ userName: this.userName });
        }
      });

      // const sendUserName = row.sendUserName;
      // console.log(row);
      // this.sendUserNameMessage({ userName: sendUserName })
      //   .then(res => {
      //     if (res.data.ok === 1) {
      //       console.log(res.data.data);

      //       this.drawerData = res.data.data;
      //       this.messageDrawer = true;
      //     }
      //   })
      //   .catch(err => {
      //     console.log("错误提示：" + err);
      //   });
    },
    setImage(row) {
      return row.sendCoverUrl;
    },
    setStatus(row) {
      return row.status === true ? "已查看" : "未查看";
    },
    setDate(row) {
      let date = new Date(row.updated);
      return date.toLocaleString("chinese", { hour12: false });
    },
    ...mapActions("user", [
      "sendUserNameMessage",
      "toggleMessageStatus",
      "getMessage",
      "sendMessageToUser",
      "getOneToOneMessage"
    ])
  }
};
</script>

<style lang="sass" scoped>
@import '@/assets/default.sass'
.message
  width: 100%
  padding: 20px
  .message-table
    width: 100%
    .title
      width: 100%
      height: 40px
      line-height: 40px
      font-size: 16px
      color: #333
      position: relative
      padding-left: 10px
      &:after
        content: ""
        width: 5px
        height: 18px
        position: absolute
        top: 11px
        left: 0
        background-color: #eb2001  
  .system-message
    width: 100%
    .title
      width: 100%
      height: 40px
      line-height: 40px
      font-size: 16px
      color: #333
      position: relative
      padding-left: 10px
      &:after
        content: ""
        width: 5px
        height: 18px
        position: absolute
        top: 11px
        left: 0
        background-color: #eb2001 
    >ul
      width: 100%
      >li
        width: 100%
        padding: 10px 0
        border-bottom: 1px solid #eee
        .send-user
          width: 100%
          @include flex(space-between,center)
          .img
            flex: 0 0 36px
            height: 36px
            overflow: hidden
            border-radius: 5px
            @include flex(center,center)
            img
              width: 100%
              height: auto
          .content
            position: relative
            flex: 1
            padding-left: 15px
            >h3
             line-height: 32px
            >p
              line-height: 20px 
              >i
                color: #eb2001  
            .status   
              position: absolute
              right: 5px
              top: 20px    
              color: #2eb037  
        .text
          line-height: 20px
          padding: 10px 0 10px 50px
          color: #0487dc
        .look
          width: 100%
          line-height: 30px
          height: 35px
          @include flex(space-between,center)
          .this-click
            color: #eb2001
            cursor: pointer
            &:hover
              text-decoration: underline
        &:last-child
          border: none
</style>


<style lang="sass">
@import '@/assets/default.sass'
.message
  .message-table
    .img
      width: 32px
      height: 32px
      overflow: hidden
      border-radius: 5px
      @include flex(center,center)
      img
        width: 100%
        height: auto
  .el-drawer
    width: 100%
    padding: 40px 15px
    .drawer-content
      width: 100%
      .send-user
        width: 100%
        padding: 10px 0
        @include flex(space-between,center)
        .send-user-left
          flex: 0 0 42px
          height: 42px
          overflow: hidden
          border-radius: 5px
          @include flex(center,center)
          >img
            width: 100%
            height: auto
        .send-user-right
          flex: 1
          margin-left: 10px
          >h3
            height: 30px
      .send-body
        width: 100%
        padding: 10px
        min-height: 180px
        background-color: #eee
        overflow: auto
        line-height: 20px
      .return-message
        width: 100%
        margin-top: 10px
        .btn
          width: 100%
          height: 40px
          @include flex(space-between,center)
        .history
          width: 100%
          margin-top: 10px
          border-top: 1px solid #eee
          >ul
            width: 100%
            >h3
              width: 100%
              line-height: 40px
              height: 40px
              position: relative
              padding-left: 10px
              &:before
                content: "",
                position: absolute
                width: 5px
                height: 16px
                top: 12px
                left: 0
                background-color: #eb2001
            >li
              width: 100%
              line-height: 20px
              min-height: 30px
              background-color: #eee
              padding: 0 5px
              margin: 10px 0
              border-radius: 5px
              @include flex(flex-start,center)
            .active
              background-color: rgba(16,88,124,.3)
              color: #333
</style>
